using System;
using NHibernate;
using NHibernate.Cfg.Loquacious;
using StructureMap;
using StructureMap.Configuration.DSL;
using Caramel.Linq;
//using Caramel.NHibernate.Linq.Functions;

namespace Caramel.NHibernate.StructureMap
{
	public class NHibernateRegistry : Registry
	{
		public NHibernateRegistry(global::NHibernate.Cfg.Configuration configuration)
		{
			//configuration.LinqToHqlGeneratorsRegistry<CaramelLinqToHqlGeneratorsRegistry>();

			this.For<global::NHibernate.Cfg.Configuration>().
				Singleton().
				Use(configuration);

			this.For<ISessionFactory>().
				Singleton().
			    Use(configuration.BuildSessionFactory());

			this.
				For<IUnitOfWorkFactory>().
				Singleton().
				Use(X => new NHibernateUnitOfWorkFactory(X.GetInstance<ISessionFactory>()));

			// Register our default repository for mapped types
			configuration.
				ClassMappings.
				Each(
					c =>
					this.For(
						typeof(IRepository<>).
							MakeGenericType(c.MappedClass)
					).
					Singleton().
					Use(
						typeof(NHibernateRepository<>).
							MakeGenericType(c.MappedClass)
					)
			);
		}
	}
}
